//
//  NotificationService.swift
//  serviceNotification
//
//  Created by wsj on 17/8/10.
//  Copyright © 2017年 wsj. All rights reserved.
//

import UserNotifications
import UIKit
/// 提供https请求https://bmob-cdn-11544.b0.upaiyun.com/2017/08/10/e7d6b26540785fb980c7a467e4920c82.jpg
/// https://bmob-cdn-11544.b0.upaiyun.com/2017/08/10/a95ba73640d0a952803067565f36032f.gif
/**
 调用自定义UI推送的容
 {"aps":{"alert":"Testing.. (5)","badge":1,"sound":"default","category":"wj_sevenSeconds_customUI","mutable-content":1},"image":"https://bmob-cdn-11544.b0.upaiyun.com/2017/08/10/a95ba73640d0a952803067565f36032f.gif"}
 调用系通UI推送的容
 {"aps":{"alert":"Testing.. (5)","badge":1,"sound":"default","mutable-content":1},"image":"https://bmob-cdn-11544.b0.upaiyun.com/2017/08/10/a95ba73640d0a952803067565f36032f.gif"}
 */
/**
    注意:
        0.如果通知想被扩展拦截,通知里面的‘mutable-content’字段必须是‘1’
        0.所有的附件连接必须是https的，http的是不可以的
        1.下载附件的时间不会超过30秒
        2.附件的大小同样也有限制，音频5M  图像10M支持  jepg，png。git   视频50M
        3.如果是我设计，我一般不喜欢在这下载，如果下载失败，会造成推送不成功，也会也会造成崩溃。一般我喜欢先把需要推送的图片下载到本地，使用偏好设置或者sql记录
            下载位置，推送来了直接展现即可
        如果非要即使下载，建议：当图片下载失败的时候，我们可以使用图片进行替代（如果考虑到文字和图片不符合），如果真是这样，真的可以去打产品
 */

/**
 通知运用：iOS10.0以后，我们可以根据notification servicer 来获取用户后台显示的通知数量，来实现删除，更新，合并通知条目
 如果是本地通知的话。我们可以直接在添加通知的request的时候，来获取用户的通知信息
 1.我们可以拿到通知通信unnotificationCenter.curren();
 // 得到通知中心添加的categories
 func getNotificationCategories(completionHandler: @escaping (Set<UNNotificationCategory>) -> Swift.Void)
 /// 得到用户对待通知的响应，拒绝，允许等
 func getNotificationSettings(completionHandler: @escaping (UNNotificationSettings) -> Swift.Void)
 /// 得到未到达的通知请求
 func getPendingNotificationRequests(completionHandler: @escaping ([UNNotificationRequest]) -> Swift.Void)
 /// 根据Request、的indentifiers 移除通知request
 func removePendingNotificationRequests(withIdentifiers identifiers: [String])
 /// 移除所有的通知request
 func  removeAllPendingNotificationRequests()
 /// 得到用户手机上的用纸数组
 func getDeliveredNotifications(completionHandler: @escaping ([UNNotification]) -> Swift.Void)
 ///  移除掉通知根据通知的indentifier
 func removeDeliveredNotifications(withIdentifiers identifiers: [String])
 /// 移除掉所有的通知
 func removeAllDeliveredNotifications()
 */
class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
    private lazy var imagas = ["xianyu.png","222.png","111.png","333.png","444.png","cry.gif"];
    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        /// 其实一般我们使用的图片一般都是图片的一个连接，从而去下载图片，并显示出来，但是图片必须是https的
        if let bestAttemptContent = bestAttemptContent {
            let userInfo = bestAttemptContent.userInfo;
            let keys = userInfo.keys;
            var url:URL?;
            /// 加载本地还是网络图片
            if keys.contains("image"){
                let imageUrl = userInfo["image"] as! String;
                url = saveServiceImageToDic(imageUrl);
            }else{
                url = localImage();
            }
            if  (url != nil) {
                let attachment = try? UNNotificationAttachment.init(identifier: "photo", url: url!);
                if (attachment != nil){
                    bestAttemptContent.attachments = [attachment!];
                    
                }
            }
            bestAttemptContent.title = "七秒";
            bestAttemptContent.subtitle = "远程通知，七秒注";
            bestAttemptContent.body = "我是七秒，联系我可以关注简书 http://www.jianshu.com/u/e3402afea1f1";
            
                
            
            /// 获取通知内容从而来操作通知
           /// let center = UNUserNotificationCenter.current();
           /// center.getDeliveredNotifications(completionHandler: { (array:[UNNotification]) in
                
           /// })
            
            contentHandler(bestAttemptContent)
        }
    }
    func localImage()->URL?{

        let count = Int(arc4random_uniform(4));
        let imageName = imagas[count];
        let url = Bundle.main.url(forResource: imageName, withExtension: nil);
        return url;
    }
    func saveServiceImageToDic(_ stringUrl:String) -> URL? {
        let path = "image.png".wj_getCachesPath();
        let url = URL.init(fileURLWithPath: path);
        let data =  try? Data.init(contentsOf: URL.init(string: stringUrl)!);
        guard data != nil else {
            return nil;
        }
        try? data?.write(to: url);
       
        return url;
    }
    override func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }

}
